extern "C" {
#include	<luajit.h>
#include	<lualib.h>
#include	<lauxlib.h>
}

#include	"../utils/storage.h"

namespace LuaApi { namespace LuaStorage {
	static int Expire(lua_State * pL) {
		Storage::Get().Expire(lua_tonumber(pL, 1));
		return 0;
	}

	static int Get(lua_State * pL) {
		const char * pKey = lua_tostring(pL, 1);
		std::string sValue = Storage::Get().Get(pKey);
		if (sValue.empty()) return 0;
		lua_pushlstring(pL, sValue.data(), sValue.length());
		return 1;
	}

	static int Set(lua_State * pL) {
		const char * pKey = lua_tostring(pL, 1);
		size_t nLen;
		const char * pValue = lua_tolstring(pL, 2, &nLen);
		bool bNeverExpire = lua_gettop(pL) > 2 ? lua_toboolean(pL, 3) == 1 : false;
		std::string sValue(pValue, nLen);
		Storage::Get().Set(pKey, sValue, bNeverExpire);
		return 0;
	}
} }

void RegisterApi_Storage(lua_State * pL) {
	lua_newtable(pL);

	lua_pushcfunction(pL, &LuaApi::LuaStorage::Expire);
	lua_setfield(pL, -2, "expire");

	lua_pushcfunction(pL, &LuaApi::LuaStorage::Get);
	lua_setfield(pL, -2, "get");

	lua_pushcfunction(pL, &LuaApi::LuaStorage::Set);
	lua_setfield(pL, -2, "set");

	lua_setglobal(pL, "storage");
}